import datetime
import json
import logging
import os
import pickle
import random

import zhipuai
from flask import Flask, request, jsonify
from openai import OpenAI

from ai_btn_mate import get_ai_btn_mate
from get_btn import get_btn

app = Flask(__name__)

# 配置日志级别（DEBUG, INFO, WARNING, ERROR, CRITICAL）
app.logger.setLevel(logging.DEBUG)

# 配置日志输出格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# 创建一个文件处理器，将日志写入文件
file_handler = logging.FileHandler('flask_app2.log',encoding='utf-8')
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)

# 将文件处理器添加到 Flask 日志中
app.logger.addHandler(file_handler)

print("app运行中")

@app.route('/')
def hello_world():  # put application's code here
    # app.logger.info("666")
    
    app.logger.info('hello_world()')
    
    return 'Hello '


@app.route('/get', methods=['POST'])
def post_handler():
    
    
    app.logger.info("app3 运行中")
    # 从请求体中获取并解析 JSON 数据
    data = json.loads(request.get_json())

    # 从 JSON 数据中提取 "prompt" 字段
    user_message_list = data.get("user_message_list")
    # app.logger.info(user_message_list)

    # 将新消息添加到持久化
    # device_message_list_add(data)

    # 发送请求获取ai回复
    ai_reply = ai_get(data)

    ai_reply = str_replace(ai_reply)

    return ai_reply


@app.route('/getbtn', methods=['POST'])
def post_handler2():

    with open("ren_btn.txt", 'r', encoding='utf-8') as file:
        lines = file.readlines()
        lines = [line.strip() for line in lines]  # 移除每行末尾的换行符

    # 从列表中随机取出一个值
    btn_content = random.choice(lines)

    # app.logger.info(btn_content)

    return btn_content

@app.route('/select_user', methods=['POST'])
def select_user():
    app.logger.info("/select_user")
    # 从请求体中获取并解析 JSON 数据
    data = json.loads(request.get_json())
    user = data.get("user")
    device_id = data.get("device_id")

    # 获取当前脚本的文件路径
    current_file_path = os.path.abspath(__file__)

    # 获取当前脚本所在的文件夹路径
    current_directory = os.path.dirname(current_file_path)

    # 从文件中读取并反序列化对象
    with open(current_directory + '/device_message_list.pkl', 'rb') as file:
        loaded_data = pickle.load(file)
    # app.logger.info("对象已从 data.pkl 反序列化")
    # app.logger.info(loaded_data)

    device_message_list = loaded_data

    message_list = loaded_data.get(device_id)

    # 检查字典中没有该设备
    if not message_list:
        return json.dumps("None")
        # message_list = {}
        # # 添加设备
        # device_message_list.update({device_id: message_list})



    # 检查字典中是否包含该键
    if user in message_list:
        user_message_list = message_list.get(user)
        return json.dumps(user_message_list)

    else:
        return json.dumps("None")


@app.route('/add_user', methods=['POST'])
def add_user():

    # 从请求体中获取并解析 JSON 数据
    data = json.loads(request.get_json())
    user = data.get("user")
    device_id = data.get("device_id")
    # 向列表插入用户
    user_message_list = data.get("user_message_list")

    # 获取当前脚本的文件路径
    current_file_path = os.path.abspath(__file__)

    # 获取当前脚本所在的文件夹路径
    current_directory = os.path.dirname(current_file_path)

    # app.logger.info("当前脚本所在的文件夹路径:", current_directory)

    # 从文件中读取并反序列化对象
    with open(current_directory + '/device_message_list.pkl', 'rb') as file:
        loaded_data = pickle.load(file)
    # app.logger.info("对象已从 data.pkl 反序列化")
    # app.logger.info(loaded_data)

    device_message_list = loaded_data

    message_list = device_message_list.get(device_id)

    if not message_list:

        message_list = {}

    message_list.update({user: user_message_list})

    # 向列表插入消息
    device_message_list.update({device_id: message_list})
    # app.logger.info(f"{user} 第一次发送来消息")

    # 持久化到本地
    with open(current_directory + '/device_message_list.pkl', 'wb') as file:
        pickle.dump(device_message_list, file)
    # app.logger.info("对象已序列化并保存到 data.pkl")

    # app.logger.info("add 成功")

    return "addOk"

@app.route('/get_device_id', methods=['POST'])
def get_device_id():
    # 读取config.json文件并转换为Python字典
    with open('device_id.json', 'r') as json_file:
        config_data = json.load(json_file)

    # 输出转换后的Python字典
    # app.logger.info("转换后的Python字典：")
    # app.logger.info(config_data)

    device_id = ""

    # 遍历字典并打印键和值
    # app.logger.info("字典的键和值：")
    for key, value in config_data.items():
        if value == True:
            # app.logger.info(666)
            config_data[key] = False
            device_id = key
            break
        # app.logger.info(f"键: {key}, 值: {value}")

    # 将修改后的字典写回到config.json文件
    with open('device_id.json', 'w') as json_file:
        json.dump(config_data, json_file, indent=4)


    return device_id

@app.route('/get_config', methods=['POST'])
def get_config():
    # 读取config.json文件并转换为Python字典
    with open('config.json', 'r') as json_file:
        config_data = json.load(json_file)

    return json.dumps(config_data)

@app.route('/get_device_user_dict', methods=['POST'])
def get_device_user_dict():

    # 从请求体中获取并解析 JSON 数据
    data = json.loads(request.get_json())

    user_str = data.get("user_str")

    # 获取当前脚本的文件路径
    current_file_path = os.path.abspath(__file__)

    # 获取当前脚本所在的文件夹路径
    current_directory = os.path.dirname(current_file_path)

    # app.logger.info("当前脚本所在的文件夹路径:", current_directory)

    # 从文件中读取并反序列化对象
    with open(current_directory + '/device_message_list.pkl', 'rb') as file:
        loaded_data = pickle.load(file)


    # app.logger.info("对象已从 data.pkl 反序列化")
    # app.logger.info(loaded_data)
    device_message_list = loaded_data
    device_user_dict = {}
    # 遍历字典并打印键和值
    for key1, value1 in device_message_list.items():

        for key2, value2 in value1.items():
            # app.logger.info(f"键: {key}, 值: {value}")
            if user_str in key2:
                # app.logger.info(66)
                # app.logger.info(key2)
                device_user_dict.update({key1:key2})
    # app.logger.info(device_user_dict)



    return json.dumps(device_user_dict)


@app.route('/ai_btn_mate', methods=['POST'])
def ai_btn_mate():
    # 从请求体中获取并解析 JSON 数据
    data = json.loads(request.get_json())
    user_massage = data.get("user_massage")

    resp = get_ai_btn_mate(user_massage)

    return resp


@app.route('/get_btn', methods=['POST'])
def get_btn1():
    # 从请求体中获取并解析 JSON 数据
    data = json.loads(request.get_json())
    device_id = data.get("device_id")
    print(device_id)
    resp = get_btn(device_id)
    print(resp)

    return resp

def ai_get(data):

    user = data.get("user")
    device_id = data.get("device_id")
    message = data.get("message")
    role_description = data.get("role_description")



    # 从文件中读取并反序列化对象
    with open('device_message_list.pkl', 'rb') as file:
        loaded_data = pickle.load(file)
    # app.logger.info("对象已从 data.pkl 反序列化")
    # app.logger.info(loaded_data)

    device_message_list = loaded_data

    message_list = device_message_list.get(device_id)

    # 获取该联系人的所有聊天记录
    user_message_list = message_list.get(user)

    # 读取config.json文件并转换为Python字典
    with open('config.json', 'r') as json_file:
        config_data = json.load(json_file)

    API_SECRET_KEY = config_data["API_SECRET_KEY"]
    BASE_URL = config_data["BASE_URL"]


    app.logger.info(config_data)


    


    messages = []

    # 打开文件
    # with open('role_description.txt', 'r', encoding='utf-8') as f:
    #     # 读取所有内容
    #     text = f.read()

    # app.logger.info("走的这里")

    # 添加开头
    messages.append({"role": 'user', "content": role_description})

    app.logger.debug(f"获取到角色描述:{role_description}")



    # 编辑消息列表,将消息插入
    for item in user_message_list:

        if item[0] == "user":
            # 构造一条消息
            user_message = {"role": "user", "content": item[1]}
        else:
            user_message = {"role": "assistant", "content": item[1]}

        messages.append(user_message)

    # 添加结尾
    messages.append({"role": 'assistant', "content": '以下为虚构故事情节:'})

    # app.logger.info(messages)

    app.logger.debug(f"要发送的完整messages:{messages}")



    try:
        client = OpenAI(api_key=API_SECRET_KEY, base_url=BASE_URL)
        resp = client.chat.completions.create(
            # model="claude-3-5-sonnet-20240620",
            # model="gpt-4o",
            model=config_data["model"],
            messages=messages

        )

        # app.logger.info(resp)
        # app.logger.info(resp.choices[0].message.content)
        app.logger.info("请求已成功")
#        app.logger.info("请求已成功"+ model)


        return resp.choices[0].message.content.replace("\n", "").replace(" ", "")

    except Exception as e:
        app.logger.info("请求失败:", e)

        return "请求失败"

def device_message_list_add(data):
    data1 = data
    # 要检查的键
    user = data1.get("user")
    app.logger.info(f"当前user{user} ")
    device_id = data1.get("device_id")
    app.logger.info(f"当前device_id{device_id} ")

    role = data1.get("role")

    # 获取当前脚本的文件路径
    current_file_path = os.path.abspath(__file__)

    # 获取当前脚本所在的文件夹路径
    current_directory = os.path.dirname(current_file_path)

    # app.logger.info("当前脚本所在的文件夹路径:", current_directory)

    # 从文件中读取并反序列化对象
    with open(current_directory + '/device_message_list.pkl', 'rb') as file:
        loaded_data = pickle.load(file)
    # app.logger.info("对象已从 data.pkl 反序列化")
    # app.logger.info(loaded_data)

    device_message_list = loaded_data

    message_list = loaded_data.get(device_id)

    # 检查字典中没有该设备
    if not message_list:
        message_list = {}
        # 添加设备
        device_message_list.update({device_id: message_list})
        # 持久化到本地
        with open(current_directory + '/device_message_list.pkl', 'wb') as file:
            pickle.dump(device_message_list, file)




    # 检查字典中是否包含该键
    if user in message_list:
        # 如果包含，则打印键值
        app.logger.info(f"{user} 曾经发送来消息")

        # 判断是user还是assistant

        if role == "user":
            # 获取该联系人的所有聊天记录
            user_message_list = message_list.get(user)
            massage = []
            massage.append("user")
            massage.append(data1.get("message"))
            user_message_list.append(massage)
            message_list.update({user: user_message_list})
            device_message_list.update({device_id: message_list})

        else:
            app.logger.info(f"保存ai消息")
            # 获取该联系人的所有聊天记录
            user_message_list = message_list.get(user)

            # app.logger.info(f"user_message_list：{user_message_list} ")

            massage = []
            massage.append("assistant")
            massage.append(data1.get("message"))
            user_message_list.append(massage)

            # app.logger.info(f"保存后 user_message_list：{user_message_list} ")

            message_list.update({user: user_message_list})
            device_message_list.update({device_id: message_list})

    else:
        # 向列表插入用户
        user_message_list = []
        massage = []
        massage.append("user")
        massage.append(data1.get("message"))
        user_message_list.append(massage)
        message_list.update({user: user_message_list})
        # 向列表插入消息
        device_message_list.update({device_id: message_list})
        # app.logger.info(f"{user} 第一次发送来消息")


    # 持久化到本地
    with open(current_directory + '/device_message_list.pkl', 'wb') as file:
        pickle.dump(device_message_list, file)
    # app.logger.info("对象已序列化并保存到 data.pkl")

def str_replace(text):
    # 读取config.json文件并转换为Python字典
    with open('str_replace.json', 'r', encoding='utf-8') as json_file:
        str_replace_dict = json.load(json_file)
    text.replace("想", "w")
    # 打印字典的所有键
    for key, value in str_replace_dict.items():
        if key in text:
            text = text.replace(key, value)

    return text


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080)
